import oss2
from django.conf import settings


def connect_oss_client():
    """连接阿里云 OSS 客户端"""
    auth = oss2.Auth(
        access_key_id=settings.ALIYUN_OSS_ACCESS_KEY_ID,
        access_key_secret=settings.ALIYUN_OSS_ACCESS_KEY_SECRET
    )
    bucket = oss2.Bucket(
        auth,
        endpoint=settings.ALIYUN_OSS_ENDPOINT,
        bucket_name=settings.ALIYUN_OSS_BUCKET_NAME
    )
    return bucket


def save_to_oss(content_type, oss_client, file_data, folder_prefix):
    """保存文件到 OSS，并返回访问 URL"""
    import uuid
    import datetime

    # 生成唯一文件名（示例：predict_2023-10-01_abc123.jpg）
    filename = f"predict_{datetime.datetime.now().strftime('%Y-%m-%d')}_{uuid.uuid4().hex}.{content_type.split('/')[-1]}"
    object_key = f"{folder_prefix}/{filename}"

    # 上传文件
    oss_client.put_object(
        object_key,
        file_data,
        headers={'Content-Type': content_type}
    )

    # 生成公开访问 URL（需确保Bucket为公共读或配置CDN）
    return f"https://{oss_client.bucket_name}.{oss_client.endpoint.replace('http://', '')}/{object_key}"